import { Component, OnInit } from '@angular/core';
import { InterceptorService } from "../../share/interceptor.service";
import { SerachRegionInfo } from 'app/models/search-region-info';
import { Router } from "@angular/router";
import { AuthGuardService } from "../../share/auth-guard.service";
declare var AMap: any;
declare var AMapUI: any;


@Component({
  selector: 'app-search-region',
  templateUrl: './search-region.component.html',
  styleUrls: ['./search-region.component.css']
})
export class SearchRegionComponent implements OnInit {

  constructor(
    private router: Router,
    private http: InterceptorService,
    private authGuardService: AuthGuardService) { }

  ngOnInit() {
    // this.getData();//页面初次加载的时候初始化表格，默认查询所有数据库中的相关毕业生
    this.getOptions();


    /****************************************地图初始化********************** */
    var map = new AMap.Map("gaodemap-container", {
      resizeEnable: true
    });
      //详情查询
      var placeSearch = new AMap.PlaceSearch();  //构造地点查询类
      placeSearch.getDetails("B0FFGH7LE2", function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          placeSearch_CallBack(result);
        }
      });

    var infoWindow = new AMap.InfoWindow({
      autoMove: true,
      offset: { x: 0, y: -30 }
    });

    //回调函数
    function placeSearch_CallBack(data) {
      console.log(data);
      var poiArr = data.poiList.pois;
      console.log(poiArr);
      //添加marker
      var marker = new AMap.Marker({
        map: map,
        position: poiArr[0].location
      });
      map.setCenter(marker.getPosition());
      infoWindow.setContent(createContent(poiArr[0]));
      infoWindow.open(map, marker.getPosition());
    }
    function createContent(poi) {  //信息窗体内容
      var s = [];
      s.push("<b>名称：" + "大米时代第一校区" + "</b>");
      s.push("地址：" + poi.address);
      s.push("电话：" + "12345678910");
      s.push("类型：" + poi.type);
      return s.join("<br>");
    }
  }


  /****************************变量声明******************************************* */
  regionInfo: SerachRegionInfo = new SerachRegionInfo();//查询所需要的变量





  /*************************************************省市县的三级联动************************ */

  getOptions() {
    this.getProvinceOptions();
    this.getTermOptions();
    this.getRegionOptions();
  }
  provinceOptions: any[] = [];

  getProvinceOptions() {
    let url = "graduate-web/administrativeRegion/selectProvince";
    // let url = "http://192.168.21.204:8081/graduate-web/administrativeRegion/selectProvince"
    this.http.get(url).subscribe(
      res => {
        console.log("123");
        if (res.json().code == "0000") {
          this.provinceOptions = res.json().data;
        }
      }
    );
  }

  changeProvice(proviceId: string) {
    this.getCityOptions(proviceId)
  }

  cityOptions: any[] = [];

  getCityOptions(proviceId: string) {
    let url = "graduate-web/administrativeRegion/selectSubRegionById/" + proviceId;
    this.http.get(url, "GET").subscribe(
      res => {
        if (res.json().code == "0000") {
          this.cityOptions = res.json().data;
        }
      }
    );
  }

  changeCity(cityId: string) {
    this.getCountyOptions(cityId);
  }

  countyOptions: any[] = [];

  getCountyOptions(cityId: string) {
    let url = "graduate-web/administrativeRegion/selectSubRegionById/" + cityId;
    this.http.get(url, "GET").subscribe(
      res => {
        if (res.json().code == "0000") {
          this.countyOptions = res.json().data;
        }
      }
    );
  }


  /**
   * 获取期数下拉框
   */

  termOptions: string[][];

  getTermOptions() {
    let url = "graduate-web/dictionary/selectGrade";
    this.http.get(url, "GET").subscribe(
      res => {
        if (res.json().code == "0000") {
          this.termOptions = res.json().data;
        }
      }
    );
  }


  /**
   *获取选择地域的下拉框
   */
  regionOptions: string[] = [];

  getRegionOptions() {
    let url = "graduate-web/dictionary/selectAddressType";
    this.http.get(url, "GET").subscribe(
      res => {
        if (res.json().code == "0000") {
          this.regionOptions = res.json().data;
        }
      }
    );
  }





  public provinceOptionList: RegionList[] = [];

  getRegionList() {
    let region=new Region();
    let proviceName=new Region();
    let cityName=new Region();
    let countyName=new Region();
    //查找省的名称
    if(this.isEmpty(this.regionInfo.proviceId)){
      proviceName.name="";
    }else{
      proviceName=this.provinceOptions.find(i=>i.id==this.regionInfo.proviceId);
    }
 
    if(this.isEmpty(this.regionInfo.cityId)){
      cityName.name="";
    }else{
      cityName=this.cityOptions.find(i=>i.id==this.regionInfo.cityId);
    }

    if(this.isEmpty(this.regionInfo.countyId)){
      countyName.name="";
    }else{
      countyName=this.countyOptions.find(i=>i.id==this.regionInfo.countyId);
    }
   
    console.log(proviceName.name);
    console.log(cityName.name);
    console.log(countyName.name);

    let addressName="";
    addressName=proviceName.name+cityName.name+countyName.name;
    console.log(addressName);
    if(this.isEmpty(this.regionInfo.name)){
      region.name="%20";
    }else{
      region.name=this.regionInfo.name;
    }

    if(this.isEmpty(this.regionInfo.sex)){
      region.sex="%20";
    }else{
      region.sex=this.regionInfo.sex;
    }

    //判断地域类型id
    if(this.isEmpty(this.regionInfo.regionId)){
      region.regionName="%20";
    }else{
      region.regionName=this.regionInfo.regionId;
    }


    //判断年级是否为空
    if(this.isEmpty(this.regionInfo.termId)){
      region.grade="%20";
    }else{
      region.grade=this.regionInfo.termId;
    }


    //判断地址字符串是否为空
    if(this.isEmpty(addressName)){
      region.dictionaryAddress="%20";
    }else{
      region.dictionaryAddress=addressName;
    }



    let url = "graduate-web/personalInfo/selectPersonRegion/"+region.name+"/"+region.sex+"/"+region.regionName+"/"+region.grade+"/"+region.dictionaryAddress;
    // let url = "http://192.168.21.204:8081/graduate-web/administrativeRegion/selectProvince"
    this.http.get(url).subscribe(
      res => {
        if (res.json().code == "0000") {
          this.provinceOptionList = res.json().data;
          console.log(this.provinceOptionList)
        }
      }
    );
  }


  /************************************搜索按钮事件********************************* */

  checkBoy: boolean = false;
  checkGirl: boolean = false;

  search() {

    console.log(this.checkBoy);
    console.log(this.checkGirl);
    console.log(this.regionInfo);
    if (this.checkBoy == true && this.checkGirl == false) {
      this.regionInfo.sex = "男";
    } else if (this.checkGirl == true && this.checkBoy == false) {
      this.regionInfo.sex = "女";
    }
    
    //地图加载显示

    var map = new AMap.Map("gaodemap-container", {
      resizeEnable: true
    });
    var marker = new Array();
    var windowsArr = new Array();
    var resultStr = "";
    var poiArr:any;
    this.getRegionList();
    poiArr = this.provinceOptionList;
    //回调函数

    // var resultCount = poiArr.length;
    for (var i = 0; i < this.provinceOptionList.length; i++) {
      resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"https://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h3>";
      resultStr += createContent(poiArr) + "</td></tr></table></div>";
      addmarker(i, poiArr[i]);
    }
    map.setFitView();


    //添加marker&infowindow
    function addmarker(i, d) {
      var lngX = d.lng;
      var latY = d.lat;
      var markerOption = {
        map: map,
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b" + (i + 1) + ".png",
        position: [lngX, latY],
        topWhenMouseOver: true

      };
      var mar = new AMap.Marker(markerOption);
      marker.push([lngX, latY]);

      var infoWindow = new AMap.InfoWindow({
        content: "<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + createContent(d),
        autoMove: true,
        offset: new AMap.Pixel(0, -30)
      });
      windowsArr.push(infoWindow);
      var aa = function (e) {
        infoWindow.open(map, mar.getPosition());
      };
      mar.on("mouseover", aa);
    }
    //窗体内容
    function createContent(region: any) {
      var s = [];
      s.push("姓名：" + region.name);
      s.push("性别：" + region.sex);
      s.push("期数：" + region.gradeName);
      s.push("电话：" + region.phone);
      s.push("地域类型：" + region.name);
      s.push("地址：" + region.regionAddress);
      return '<div>' + s.join("<br>") + '</div>';
    }

    function openMarkerTipById1(pointid, thiss) {  //根据id 打开搜索结果点tip
      thiss.style.background = '#CAE1FF';
      windowsArr[pointid].open(map, marker[pointid]);
    }
    function onmouseout_MarkerStyle(pointid, thiss) { //鼠标移开后点样式恢复
      thiss.style.background = "";
    }
  }



  isEmpty(obj:string){
    if (obj == undefined || obj == null || obj.trim() == "") {
      return true;
    }
    return false;
  }

}



export class RegionList {
  id: string;
  name:string;
  sex:string;
  phone:string;
  poi: string;
  lng: string;
  lat: string;
  dictAddressType:string;
  gradeName:string;
  regionAddress:string;

}



export class Region{
   name:string;
   sex:string;
   regionName:string;
   grade:string;
   dictionaryAddress:string;
}